package com.xyyl.patient.service.user;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xyyl.patient.core.constant.AppEnum;
import com.xyyl.patient.core.util.DateUtils;
import com.xyyl.patient.entity.user.AccountRecord;
import com.xyyl.patient.entity.user.RechargeOrder;
import com.xyyl.patient.entity.user.User;
import com.xyyl.patient.mapper.user.AccountRecordMapper;
import com.xyyl.patient.mapper.user.RechargeOrderMapper;
import com.xyyl.patient.mapper.user.UserMapper;

/**
 * @projectName:xyyl-patient-service
 * @ClassName: RechargeOrderServiceImp
 * @Description: 订单充值Service
 * @author chen
 * @date 2017年8月22日
 *
 */
@Service("rechargeOrderService")
public class RechargeOrderServiceImp implements RechargeOrderService {

	@Autowired
	private RechargeOrderMapper rechargeOrderMapper;

	@Autowired
	private AccountRecordMapper accountRecordMapper;

	@Autowired
	private UserMapper userMapper;

	@Override
	public int saveRechargeOrder(RechargeOrder rechargeOrder) {

		rechargeOrder.setCreatetime(DateUtils.currentDatetime());
		rechargeOrder.setStatus(AppEnum.common.Recharge_status_not.getValue());
		rechargeOrder.setPayType(AppEnum.common.Order_payType_wx.getValue());
		return rechargeOrderMapper.insert(rechargeOrder);
	}

	/**
	 * 1.确认支付，更新订单状态； 2.新增账户流水； 3.更新账户余额
	 */
	public int confirmPay(RechargeOrder rechargeOrder) {

		/** 1.查询账户信息 **/
		User user = userMapper.queryUserByOption(null, rechargeOrder.getOpenid());
		BigDecimal beforeBalance = user.getAccountbalance() == null ? new BigDecimal("0.00") : user.getAccountbalance();

		/** 2.更新用户账户余额 **/
		BigDecimal rechargeFree = rechargeOrder.getRechargeAmount();
		BigDecimal afterBalance = beforeBalance.add(rechargeFree).setScale(2);
		user.setAccountbalance(afterBalance);
		userMapper.update(user);

		/** 3.保存账户流水信息 **/
		AccountRecord accountRecord = new AccountRecord();
		accountRecord.setAmount(rechargeFree);
		accountRecord.setOrdersn(rechargeOrder.getOrdersn());
		accountRecord.setChangetype(AppEnum.common.Order_changetype_in.getValue());
		accountRecord.setPatientid(user.getId());
		accountRecord.setIncometype(AppEnum.common.Order_changetype_out.getValue());
		accountRecord.setTotalamountBefore(beforeBalance);
		accountRecord.setTotalamountAfter(afterBalance);
		accountRecord.setCreatetime(DateUtils.currentDatetime());
		accountRecordMapper.insert(accountRecord);

		/** 4.更新支付信息 **/
		return rechargeOrderMapper.update(rechargeOrder);
	}

	@Override
	public RechargeOrder queryOrderDetail(String ordersn, String openid) {
		return rechargeOrderMapper.queryOrderDetailBySn(openid, ordersn);
	}

}
